import { sign } from 'jsonwebtoken'

export default defineEventHandler(async (event) => {
  const { name, passwd } = await readBody(event)
  let user = await event.context.prisma.user.findFirst({ where: { name } })
  if (!user) {
    user = await event.context.prisma.user.create({
      data: {
        name,
        passwd
      }
    })
  }
  if (user.passwd !== passwd) {
    throw createError({ statusCode: 403 })
  }
  return {
    token: sign({ id: user.id, name }, useRuntimeConfig().secret, { expiresIn: '1d' })
  }
})
